import React, { useState, useEffect } from 'react';
import { Form, Button, Card, Alert } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import AuthService from '../services/AuthService';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const navigate = useNavigate();

  // 在组件加载时检查登录状态
  useEffect(() => {
    const checkAuthStatus = () => {
      if (AuthService.isAuthenticated()) {
        // 如果已经登录，根据角色跳转到相应页面
        const user = AuthService.getCurrentUser();
        console.log('登录页面检测到用户已登录:', user);
        
        if ((user && user.role === 'ROLE_ADMIN') || 
            (user && user.user && user.user.role === 'ROLE_ADMIN')) {
          console.log('检测到已登录的管理员，自动跳转');
          navigate('/admin');
        } else {
          console.log('检测到已登录的普通用户，自动跳转');
          navigate('/todos');
        }
      }
    };
    
    checkAuthStatus();
  }, [navigate]);

  const handleLogin = (e) => {
    e.preventDefault();
    setMessage('');
    setLoading(true);

    if (!username || !password) {
      setMessage('请填写所有字段');
      setLoading(false);
      return;
    }

    AuthService.login(username, password)
      .then(response => {
        console.log('普通用户登录响应:', response);
        if (response.code === 200) {
          const user = AuthService.getCurrentUser();
          console.log('普通用户登录成功，用户信息:', user);
          
          // 检查账户是否被禁用
          if ((user && user.enabled === false) || 
              (user && user.user && user.user.enabled === false)) {
            console.log('账户已被禁用');
            setMessage('您的账户已被管理员禁用，请联系管理员解决');
            AuthService.logout(); // 清除登录信息
            setLoading(false);
            return;
          }
          
          // 登录成功后触发自定义事件，通知导航栏更新状态
          window.dispatchEvent(new Event('login-state-change'));
          
          // 如果是管理员，跳转到管理界面
          if ((user && user.role === 'ROLE_ADMIN') || 
              (user && user.user && user.user.role === 'ROLE_ADMIN')) {
            console.log('检测到管理员，跳转到管理界面');
            navigate('/admin');
          } else {
            console.log('检测到普通用户，跳转到待办事项');
            navigate('/todos');
          }
        } else {
          setMessage(response.message || '登录失败，请检查您的账号和密码');
          setLoading(false);
        }
      })
      .catch(error => {
        console.error('普通用户登录错误:', error);
        const resMessage = (error.response && 
                           error.response.data && 
                           error.response.data.message) || 
                           error.message || 
                           error.toString();
        setMessage(resMessage);
        setLoading(false);
      });
  };

  return (
    <Card className="p-4 mx-auto mt-5" style={{ maxWidth: '500px' }}>
      <Card.Body>
        <h2 className="text-center mb-4">登录</h2>
        
        {message && (
          <Alert variant="danger" className="mb-4">
            {message}
          </Alert>
        )}

        <Form onSubmit={handleLogin}>
          <Form.Group className="mb-3" controlId="formUsername">
            <Form.Label>用户名</Form.Label>
            <Form.Control
              type="text"
              placeholder="请输入用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </Form.Group>

          <Form.Group className="mb-3" controlId="formPassword">
            <Form.Label>密码</Form.Label>
            <Form.Control
              type="password"
              placeholder="请输入密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </Form.Group>

          <Button 
            variant="success" 
            type="submit" 
            className="w-100" 
            disabled={loading}
            style={{backgroundColor: '#2e7d32', borderColor: '#2e7d32'}}
          >
            {loading ? '登录中...' : '登录'}
          </Button>
        </Form>
        
        <div className="mt-3 text-center">
          <span>还没有账号？</span>{' '}
          <Button 
            variant="link" 
            className="p-0" 
            onClick={() => navigate('/register')}
            style={{color: '#2e7d32'}}
          >
            立即注册
          </Button>
        </div>
      </Card.Body>
    </Card>
  );
};

export default Login; 